<?php

namespace app\admin\controller\resume;

use app\common\controller\Backend;
use Knp\Snappy\Pdf;
use think\Config;

/**
 * 简历基本信息
 *
 * @icon fa fa-circle-o
 */
class Resume extends Backend
{
    protected $noNeedLogin = ['preview'];
    /** @var \app\admin\model\resume\Basicinfo */
    protected                                           $model;
    protected \app\admin\model\resume\Careerobjective   $careerobjectiveModel;
    protected \app\admin\model\resume\Education         $educationModel;
    protected \app\admin\model\resume\Workexp           $workexpModel;
    protected \app\admin\model\resume\Projectexperience $projectexperienceModel;
    protected \app\admin\model\resume\Schoolexperience  $schoolexperienceModel;
    protected \app\admin\model\resume\Trophy            $trophyModel;

    public function _initialize()
    {
        parent::_initialize();
        // 基本信息
        $this->model = new \app\admin\model\resume\Basicinfo();
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("maritalstatusList", $this->model->getMaritalstatusList());
        $this->view->assign("jobsearchstatusList", $this->model->getJobsearchstatusList());
        // 求职意向
        $this->careerobjectiveModel = new \app\admin\model\resume\Careerobjective();
        $this->view->assign("accommodationrequiredList", $this->careerobjectiveModel->getAccommodationrequiredList());
        $this->view->assign("availabilitydayList", $this->careerobjectiveModel->getAvailabilitydayList());
        // 教育背景
        $this->educationModel = new \app\admin\model\resume\Education();
        $this->view->assign("educationlevelList", $this->educationModel->getEducationlevelList());
        // 工作经历
        $this->workexpModel = new \app\admin\model\resume\Workexp();
        $this->view->assign("keepsalaryconfidentialList", $this->workexpModel->getKeepsalaryconfidentialList());
        // 项目经历
        $this->projectexperienceModel = new \app\admin\model\resume\Projectexperience();
        // 校园经历
        $this->schoolexperienceModel = new \app\admin\model\resume\Schoolexperience();
        // 获得证书
        $this->trophyModel = new \app\admin\model\resume\Trophy();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        return $this->view->fetch();
    }

    public function preview($ids = null)
    {
        $params = [
            'time'     => (int)$this->request->request('time'),
            'download' => $this->request->request('download'),
        ];

        $time   = time();
        if ($params['time'] != 0 && $time < ($params['time'] + 600)) {
            $time = $params['time'];
        }

        $download = md5('asvwtsrtbwet' . $time);

        $basicinfoModel = $this->model
            ->where(function ($query) use ($params, $download) {
                if ($params['download'] !== $download) {
                    $query->whereIn('AdminID', $this->auth->getChildrenAdminIds(true));
                }
                return $query;
            })
            ->where('BasicinfoID', $ids)->find();
        if (!$basicinfoModel) {
            $this->error(__('No Results were found'));
        }
        $educationModel = $this->educationModel->where('BasicinfoID', $basicinfoModel['BasicinfoID'])->order(['StartDate' => 'desc', 'EducationLevel' => 'desc'])->find();
        if (!$educationModel) {
            $educationModel = $this->educationModel;
        }

        $groups = [
            $this->getBasicinfoGroup($basicinfoModel, $educationModel),
            $this->getContactGroup($basicinfoModel),
            $this->getCareerobjectiveGroup($ids),
            $this->getWorkexpGroup($ids),
            $this->getEducationGroup($ids),
            $this->getCvskillGroup($basicinfoModel),
            $this->getSchoolexperienceGroup($ids),
            $this->getProjectexperienceGroup($ids),
            $this->getTrophyGroup($ids),
            $this->getCvselfGroup($basicinfoModel),
        ];

        $data = [
            'head'   => [
                'Name'            => $basicinfoModel['Name'],
                'Gender'          => $basicinfoModel['Gender_text'],
                'DateOfBirth'     => $basicinfoModel['DateOfBirth'],
                'WorkYear'        => round($basicinfoModel['WorkYear'], 1),
                'EducationLevel'  => $educationModel['EducationLevel_text'] ?? '未填写',
                'Photo'           => $basicinfoModel['Photo'],
                'JobSearchStatus' => $basicinfoModel['JobSearchStatus_text'],
            ],
            'groups' => array_filter($groups),
        ];
        $this->view->engine->layout('layout/resume');
        $this->view->assign('data', $data);
        if ($this->request->request('download') == 1) {
            $snappy = new Pdf(Config::get('wkhtmltopdf.path'));
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="' . md5(time() . mt_rand(100, 999)) . '.pdf"');
            echo $snappy->getOutput($this->request->domain() . $this->request->baseUrl() . '?ids='.$ids.'&download=' . $download . '&time=' . $time);
            exit;
        }
        return $this->view->fetch();
    }

    protected function getBasicinfoGroup(\app\admin\model\resume\Basicinfo $basicinfoModel, \app\admin\model\resume\Education $educationModel)
    {
        return [
            'title' => '基本信息',
            'icon'  => 'basicinfo',
            'infos' => [
                ['key' => '毕业院校', 'value' => $educationModel['SchoolName'] ?? '未填写'],
                ['key' => '现居住地', 'value' => $basicinfoModel['CurrentLocation']],
                ['key' => '专业', 'value' => $basicinfoModel['EducationCategory']],
                ['key' => '户口所在地', 'value' => $basicinfoModel['Residency']],
                ['key' => '身高', 'value' => round($basicinfoModel['Height'], 1) . 'CM'],
            ],
            'rows'  => [],
        ];
    }

    protected function getContactGroup(\app\admin\model\resume\Basicinfo $basicinfoModel)
    {
        return [
            'title' => '联系方式',
            'icon'  => 'contact',
            'infos' => [
                ['key' => '手机号码', 'value' => $basicinfoModel['MobileNum']],
                ['key' => '联系邮箱', 'value' => $basicinfoModel['Email']],
            ],
            'rows'  => [],
        ];
    }

    protected function getCvskillGroup(\app\admin\model\resume\Basicinfo $basicinfoModel)
    {
        if ($basicinfoModel['SpecialSkill'] == '') {
            return [];
        }
        return ['title' => '技能专长', 'icon' => 'cvskill', 'text' => $basicinfoModel['SpecialSkill'], 'infos' => [], 'rows' => []];
    }

    protected function getCvselfGroup(\app\admin\model\resume\Basicinfo $basicinfoModel)
    {
        if ($basicinfoModel['SelfAssessment'] == '') {
            return [];
        }
        return ['title' => '自我评价', 'icon' => 'cvself', 'text' => $basicinfoModel['SelfAssessment'], 'infos' => [], 'rows' => []];
    }

    protected function getCareerobjectiveGroup($BasicinfoID)
    {
        $careerobjectiveModel = $this->careerobjectiveModel->where('BasicinfoID', $BasicinfoID)->find();

        if (!$careerobjectiveModel) {
            return [];
        }

        return [
            'title' => '求职意向',
            'icon'  => 'objective',
            'infos' => (function () use ($careerobjectiveModel) {
                $infos = [];
                if ($careerobjectiveModel['ExpectedSalary'] > 0) {
                    $infos[] = ['key' => '期望月薪', 'value' => sprintf('￥%d以上', $careerobjectiveModel['ExpectedSalary'])];
                    $infos[] = ['key' => '意向地区', 'value' => $careerobjectiveModel['ExpectedJobLocation']];
                    $infos[] = ['key' => '到岗时间', 'value' => $careerobjectiveModel['AvailabilityDay_text']];
                    $infos[] = ['key' => '住房要求', 'value' => $careerobjectiveModel['AccommodationRequired_text']];
                } else {
                    $infos[] = ['key' => '意向地区', 'value' => $careerobjectiveModel['ExpectedJobLocation']];
                    $infos[] = ['key' => '到岗时间', 'value' => $careerobjectiveModel['AvailabilityDay_text']];
                    $infos[] = ['key' => '住房要求', 'value' => $careerobjectiveModel['AccommodationRequired_text']];
                    $infos[] = ['key' => '', 'value' => ''];
                }
                $infos[] = ['key' => '意向岗位', 'value' => $careerobjectiveModel['ExpectedJobFunction']];
                $infos[] = ['key' => '', 'value' => ''];
                $infos[] = ['key' => '意向行业', 'value' => $careerobjectiveModel['ExpectedJobIndustry']];
                return $infos;
            })(),
            'rows'  => [],
        ];
    }

    protected function getWorkexpGroup($BasicinfoID)
    {
        $workexpModels = $this->workexpModel->where('BasicinfoID', $BasicinfoID)->order(['StartDate' => 'desc'])->select();
        if (!$workexpModels) {
            return [];
        }

        $rows = [];
        foreach ($workexpModels as $workexpModel) {
            $rows[] = [
                'date'  => date('Y.m', strtotime($workexpModel['StartDate'])) . '-' . date('Y.m', strtotime($workexpModel['EndDate'])),
                'title' => $workexpModel['Company'],
                'infos' => (function () use ($workexpModel) {
                    $infos   = [];
                    $infos[] = ['key' => '职位名称', 'value' => $workexpModel['Title']];
                    if ($workexpModel['KeepSalaryConfidential'] == 0) {
                        $infos[] = ['key' => '月薪', 'value' => $workexpModel['Salary']];
                    } else {
                        $infos[] = ['key' => '', 'value' => ''];
                    }
                    $infos[] = ['key' => '所属行业', 'value' => $workexpModel['JobIndustry']];
                    $infos[] = ['key' => '职能类别', 'value' => $workexpModel['JobFunction']];
                    $infos[] = ['key' => '详细描述', 'value' => $workexpModel['Description']];
                    return $infos;
                })(),
            ];
        }
        return ['title' => '工作经历', 'icon' => 'workexp', 'infos' => [], 'rows' => $rows];
    }

    protected function getEducationGroup($BasicinfoID)
    {
        $educationModels = $this->educationModel->where('BasicinfoID', $BasicinfoID)->order(['StartDate' => 'desc', 'EducationLevel' => 'desc'])->select();
        if (!$educationModels) {
            return [];
        }
        $rows = [];
        foreach ($educationModels as $educationModel) {
            $rows[] = [
                'date'  => date('Y.m', strtotime($educationModel['StartDate'])) . '-' . date('Y.m', strtotime($educationModel['EndDate'])),
                'title' => $educationModel['SchoolName'],
                'infos' => [
                    ['key' => '专业', 'value' => $educationModel['Major']],
                    ['key' => '学历', 'value' => $educationModel['EducationLevel_text']],
                ],
            ];
        }
        return ['title' => '教育背景', 'icon' => 'cvedu', 'infos' => [], 'rows' => $rows];
    }

    protected function getTrophyGroup($BasicinfoID)
    {
        $trophyModels = $this->trophyModel->where('BasicinfoID', $BasicinfoID)->order(['Date' => 'desc'])->select();
        if (!$trophyModels) {
            return [];
        }
        $rows = [];
        foreach ($trophyModels as $trophyModel) {
            $rows[] = [
                'date'  => date('Y.m', strtotime($trophyModel['Date'])),
                'title' => $trophyModel['Title'],
                'infos' => [],
            ];
        }
        return ['title' => '获得证书', 'icon' => 'skilltype', 'infos' => [], 'rows' => $rows];
    }

    protected function getSchoolexperienceGroup($BasicinfoID)
    {
        $schoolexperienceModels = $this->schoolexperienceModel->where('BasicinfoID', $BasicinfoID)->order(['StartDate' => 'desc'])->select();
        if (!$schoolexperienceModels) {
            return [];
        }
        $rows = [];
        foreach ($schoolexperienceModels as $schoolexperienceModel) {
            $rows[] = [
                'date'  => date('Y.m', strtotime($schoolexperienceModel['StartDate'])) . '-' . date('Y.m', strtotime($schoolexperienceModel['EndDate'])),
                'title' => $schoolexperienceModel['Title'],
                'infos' => [
                    ['key' => '职位名称', 'value' => $schoolexperienceModel['Duty']],
                    ['key' => '', 'value' => ''],
                    ['key' => '详细描述', 'value' => $schoolexperienceModel['Description']],
                ],
            ];
        }
        return ['title' => '校园经历', 'icon' => 'train', 'infos' => [], 'rows' => $rows];
    }

    protected function getProjectexperienceGroup($BasicinfoID)
    {
        $projectexperienceModels = $this->projectexperienceModel->where('BasicinfoID', $BasicinfoID)->order(['StartDate' => 'desc'])->select();
        if (!$projectexperienceModels) {
            return [];
        }
        $rows = [];
        foreach ($projectexperienceModels as $projectexperienceModel) {
            $rows[] = [
                'date'  => date('Y.m', strtotime($projectexperienceModel['StartDate'])) . '-' . date('Y.m', strtotime($projectexperienceModel['EndDate'])),
                'title' => $projectexperienceModel['ProjectName'],
                'infos' => [
                    ['key' => '项目职责', 'value' => $projectexperienceModel['ProjectDuty']],
                    ['key' => '', 'value' => ''],
                    ['key' => '项目描述', 'value' => $projectexperienceModel['Description']],
                ],
            ];
        }
        return ['title' => '项目经验', 'icon' => 'project', 'infos' => [], 'rows' => $rows];
    }

    public function edit($BasicinfoID = null)
    {
        $basicinfo = $this->model->whereIn('AdminID', $this->auth->getChildrenAdminIds(true))->where('BasicinfoID', $BasicinfoID)->find();
        if (!$basicinfo) {
            $this->error(__('No Results were found'));
        }
        $data['basicinfo'] = $basicinfo;
        $this->view->assign('data', $data);
        return $this->view->fetch();
    }
}
